package com.aizu.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.aizu.common.Constant;
import com.aizu.controller.CommonController;
import com.aizu.entity.User;
import com.aizu.service.MasterService;
import com.aizu.service.RenterService;

public class LoginInterceptor extends HandlerInterceptorAdapter {
	private Logger log = Logger.getLogger(this.getClass());
	public static final String LAST_PAGE = "com.isp.lastPage";

	@Autowired
	private MasterService masterService;

	@Autowired
	private RenterService renterService;

	/**
	 * 在业务处理器处理请求之前被调用 如果返回false 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
	 * 如果返回true 执行下一个拦截器,直到所有的拦截器都执行完毕 再执行被拦截的Controller 然后进入拦截器链,
	 * 从最后一个拦截器往回执行所有的postHandle() 接着再从最后一个拦截器往回执行所有的afterCompletion()
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		log.debug("========== 登陆拦截器 ==========");
		String requestUri = request.getRequestURI();
		String contextPath = request.getContextPath();
		String url = requestUri.substring(contextPath.length());
		String namespace = url.substring(0, url.indexOf("/", "/mvc/".length()));// "/mvc/master"或者"/mvc/renter"
		String registerPath = contextPath + namespace + "/register.html";// 注册页

		User user = null;
		String userKey = null;// 登陆用户保存在session中的key
		if ("/mvc/master".equals(namespace) || "/mvc/main".equals(namespace))
			userKey = CommonController.MASTER;
		else if ("/mvc/renter".equals(namespace))
			userKey = CommonController.RENTER;
		user = (User) request.getSession().getAttribute(userKey);

		if (null != user) {
			log.debug("已登陆，不用拦截");
			return true;
		}

		String fromUserName = request.getParameter(Constant.FROMUSERNAME);
		if (StringUtils.isBlank(fromUserName))
			fromUserName = (String) request.getAttribute(Constant.FROMUSERNAME);
		registerPath = this.addFromUserName(registerPath, fromUserName);
		String phone = (String) request.getAttribute("phone");
		if (StringUtils.isBlank(phone) && StringUtils.isBlank(fromUserName)) {
			log.info("Interceptor未登陆拦截：没有登陆，又没有传递微信号 redirect -> " + registerPath);
			response.sendRedirect(registerPath);
			return false;
		}

		// 自动登陆
		log.info("开始自动登陆，phone: " + phone + "，fromUserName: " + fromUserName);
		if (StringUtils.isBlank(phone) && StringUtils.isNotBlank(fromUserName)) {
			// 取微信关联的手机号
			if (CommonController.MASTER.equals(userKey) || "main".equals(userKey))
				phone = this.masterService.findPhone(fromUserName);
			else if (CommonController.RENTER.equals(userKey))
				phone = this.renterService.findPhone(fromUserName);
		}
		if (StringUtils.isBlank(phone)) {
			// 到注册页面
			log.info(fromUserName + "还没有关联手机号 redirect -> " + registerPath);
			response.sendRedirect(registerPath);
			return false;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("phone", phone);
		map.put("wx_userid", fromUserName);
		try {
			if (CommonController.MASTER.equals(userKey) || "main".equals(userKey)) {
				user = this.masterService.loadUser(map);
			} else if (CommonController.RENTER.equals(userKey)) {
				user = this.renterService.loadUser(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (null != user) {
			user.setFromUserName(fromUserName);
			request.getSession().setAttribute(userKey, user);
		} else {
			log.info(phone + "对应的用户不存在，导致自动登陆失败 redirect -> " + registerPath);
			response.sendRedirect(registerPath);
			return false;
		}
		return true;
	}

	/**
	 * 在业务处理器处理请求执行完成后,生成视图之前执行的动作 可在modelAndView中加入数据，比如当前时间
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	/**
	 * 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等
	 * 
	 * 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	/**
	 * 返回/跳转前，添加fromUserName参数
	 * 
	 * @param url
	 * @param fromUserName
	 * @return
	 */
	protected String addFromUserName(String url, String fromUserName) {
		StringBuilder finalUrl = new StringBuilder(url);
		if (StringUtils.isNotBlank(fromUserName) && url.indexOf(fromUserName) == -1) {
			if (url.indexOf("?") > -1) {
				finalUrl.append("&");
			} else {
				finalUrl.append("?");
			}
			finalUrl.append("fromUserName=").append(fromUserName);
		}
		return finalUrl.toString();
	}
}
